from . import Config
import httpx
from fastapi import HTTPException
import json

class Wechat:
    def __init__(self):
        self.name = 'Wechat'

    async def get_user_info(self, code: str):
        url = f"{Config.ACCESS_TOKEN_URL}?appid={Config.Wechat_Appid}&secret={Config.Wechat_AppSecret}&code={code}&grant_type=authorization_code"
        print(url)
        response = await self.get_token(url)
        print(response)
        print("--------------------------------")
        if'openid' in response:
          if  Config.Wechat_Scope == 'snsapi_base':
            return response
          openid = response['openid']
          token = response['access_token']
          userinfo_url = f'{Config.USERINFO_URL}?access_token={token}&openid={openid}&lang=zh_CN'
          user_info = await self.get_token(userinfo_url)
          return user_info
        else:
          raise HTTPException(status_code=400, detail=json.dumps(response))
    


    async def get_token(self, url: str) -> dict:
      async with httpx.AsyncClient() as client:
          response = await client.get(url)
          response.raise_for_status()  # To raise an exception for any 4xx/5xx status code
          return response.json()